package com.ssy.lingxi.report.config;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
//entityManagerFactoryRef:指定实体管理器工厂,transactionManagerRef:指定事务管理器
//basePackages:指定该数据源的repository所在包路径
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPay",
        transactionManagerRef = "transactionManagerPay",
        basePackages = {"com.ssy.lingxi.report.repository.pay"})
public class PayConfig {

    @Resource(name = "payDataSource")
    private DataSource payDataSource;
    @Resource(name = "vendorProperties")
    private Map<String, Object> vendorProperties;

    /**
     * 配置第一数据源实体管理工厂的bean
     * @param builder EntityManagerFactoryBuilder
     * @return LocalContainerEntityManagerFactoryBean
     */
    @Bean(name = "entityManagerFactoryPay")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPay(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(payDataSource)
                //指定组合jpaProperties和hibernateProperties配置的map对象
                .properties(vendorProperties)
                //指定该数据源的实体类所在包路径
                .packages("com.ssy.lingxi.report.entity.pay")
                .persistenceUnit("reportPersistenceUnit")
                .build();
    }

    /**
     * 配置第一数据源实体管理器
     * @param builder EntityManagerFactoryBuilder
     * @return EntityManager
     */
    @Bean(name = "entityManagerPay")
    public EntityManager entityManagerPay(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPay(builder).getObject().createEntityManager();
    }

    /**
     * 配置第一数据源事务管理器
     * @param builder EntityManagerFactoryBuilder
     * @return PlatformTransactionManager
     */
    @Bean(name = "transactionManagerPay")
    public PlatformTransactionManager transactionManagerPay(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPay(builder).getObject());
    }
}

